package com.aaa.controller;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2024/7/15 22:47
 * @description：
 * @modified By：
 * @version:
 */


import cn.hutool.core.date.DateUtil;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@MultipartConfig
@WebServlet("/upload")
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String MINIO_URL = "http://192.168.145.130:9005";
    private static final String ACCESS_KEY = "root";
    private static final String SECRET_KEY = "12345678";
    private static final String BUCKET_NAME = "box-im";

    private MinioClient minioClient;

    @Override
    public void init() throws ServletException {
        super.init();
        try {
            minioClient = MinioClient.builder()
                    .endpoint(MINIO_URL)
                    .credentials(ACCESS_KEY, SECRET_KEY)
                    .build();
        } catch (Exception e) {
            throw new ServletException("Failed to initialize Minio client", e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Part filePart = request.getPart("file");
            InputStream fileContent = filePart.getInputStream();
            //获取当前
            String fileName = extractFileName(filePart);
            System.out.println("原始的文件名"+fileName);
            fileName = fileName.substring(fileName.lastIndexOf(".")+1);
            System.out.println(fileName);
            //获取当前的年月日
            String yyyyMMdd = DateUtil.format(new Date(), "yyyyMMdd");
            //拼装新的文件名
            fileName = "image/"+yyyyMMdd+"/"+ System.currentTimeMillis()+"."+fileName;
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(BUCKET_NAME)
                            .object(fileName)
                            .stream(fileContent, -1, 10485760)
                            .contentType(filePart.getContentType())
                            .build());
            //打印文件名称
            response.getWriter().println(MINIO_URL+"/"+BUCKET_NAME+"/"+fileName);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().println("Error uploading file: " + e.getMessage());
        }
    }

    private String extractFileName(Part part) {
        String contentDisposition = part.getHeader("content-disposition");
        String[] items = contentDisposition.split(";");
        for (String s : items) {
            if (s.trim().startsWith("filename")) {
                return s.substring(s.indexOf("=") + 2, s.length() - 1);
            }
        }
        return "";
    }
}
